package com.jx.gn.handler;


import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.http.HttpUtil;
import com.jx.gn.builder.TextBuilder;
import com.jx.gn.builder.VoiceBuilder;
import com.jx.gn.config.CommParams;
import com.jx.gn.config.LinkdoodProperties;
import com.jx.gn.entity.user.User;
import com.jx.gn.service.UserService;
import com.jx.gn.utils.HttpClientUtil;
import com.jx.gn.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
@Slf4j
public class MsgHandler extends AbstractHandler {

    @Autowired
    private UserService userService;

    @Autowired
    private LinkdoodHandler linkdoodHandler;

    private WxMpXmlOutMessage textHandle(WxMpXmlMessage wxMessage, WxMpService weixinService) {

        String content = "";
        boolean isMatch = ReUtil.isMatch("(http|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?", wxMessage.getContent());
        if (isMatch) {
            content = "网站正在解析处理中";
            ThreadUtil.execute( ()-> linkdoodHandler.sendHtml(wxMessage));

        } else {
            content = "消息已转发到APP";
            ThreadUtil.execute(() -> linkdoodHandler.sendText(wxMessage));
        }


        return new TextBuilder().build(content, wxMessage, weixinService);
    }

    private WxMpXmlOutMessage voiceHandle(WxMpXmlMessage wxMessage, WxMpService weixinService) {

        String content = "";
        try {
            //下载 文件
            File file = weixinService.getMaterialService().mediaDownload(wxMessage.getMediaId());
            if (null != file) {
                ThreadUtil.execute(() -> linkdoodHandler.sendVoice(file, wxMessage));
                content = "消息已转发到APP";
            } else {
                log.info("上传文件为空");
            }

        } catch (Exception e) {
            log.info("下载文件出错{}", e);
            content = "服务器异常,下载微信文件失败";
        }


        return new TextBuilder().build(content, wxMessage, weixinService);
    }

    private WxMpXmlOutMessage imageHandle(WxMpXmlMessage wxMessage, WxMpService weixinService) {

        String content = "";
        try {
            //下载 语音文件
            File file = weixinService.getMaterialService().mediaDownload(wxMessage.getMediaId());
            if (null != file) {
                ThreadUtil.execute(() -> linkdoodHandler.sendImage(file, wxMessage));
                content = "消息已转发到APP";
            } else {
                log.info("上传文件为空");
            }

        } catch (Exception e) {
            log.info("下载文件出错{}", e);
            content = "服务器异常,下载语音失败";
        }


        return new TextBuilder().build(content, wxMessage, weixinService);
    }


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {


        WxMpXmlOutMessage result = null;
        User userByWxId = userService.getUserByWxId(wxMessage.getFromUser());
        if(null==userByWxId){
            return new TextBuilder().build("您还没有绑定账号信息，请点击菜单绑定信息", wxMessage, weixinService);
        }

        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {

            switch (wxMessage.getMsgType()) {
                case XmlMsgType.TEXT:
                    result = textHandle(wxMessage, weixinService);
                    break;
                case XmlMsgType.VOICE:
                    result = voiceHandle(wxMessage, weixinService);
                    break;
                case XmlMsgType.VIDEO:
                    result =  voiceHandle(wxMessage, weixinService);
                    break;
                case XmlMsgType.IMAGE:
                    result = imageHandle(wxMessage, weixinService);
                    break;
                default:
                    result = new TextBuilder().build("消息类型错误", wxMessage, weixinService);
            }


            //TODO 可以选择将消息保存到本地
            log.info(wxMessage.getMsgType());


        }


        return result;


    }

}
